package com.crazymaker.agent.demo.trace;

import com.crazymaker.agent.demo.bytebuddy.CostTimeTracer;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.implementation.bytecode.assign.Assigner;

import java.lang.reflect.Method;

import static com.crazymaker.agent.demo.bytebuddy.CostTimeTracer.currentSpan;
import static com.crazymaker.agent.demo.bytebuddy.CostTimeTracer.newSpan;

public class TraceAspect {
    /**
     * @param target 目标类实例
     * @param clazz  目标类class
     * @param method 目标方法
     * @param args   目标方法参数
     */
    @Advice.OnMethodEnter
    public static void onMethodEnter(@Advice.This(optional = true) Object target,
                                     @Advice.Origin Class<?> clazz,
                                     @Advice.Origin Method method,
                                     @Advice.AllArguments Object[] args) {
        CostTimeTracer.SimpleSpan simpleSpan = newSpan(method);
        simpleSpan.start();

    }

    /**
     * @param target 目标类实例
     * @param clazz  目标类class
     * @param method 目标方法
     * @param args   目标方法参数
     * @param result 返回结果
     */
    @Advice.OnMethodExit(onThrowable = Throwable.class)
    public static void onMethodExit(@Advice.This(optional = true) Object target,
                                    @Advice.Origin Class<?> clazz,
                                    @Advice.Origin Method method,
                                    @Advice.AllArguments Object[] args,
                                    @Advice.Return(typing = Assigner.Typing.DYNAMIC) Object result) {

        CostTimeTracer.SimpleSpan simpleSpan = currentSpan();
        simpleSpan.end();

    }
}